package main

import (
	"github.com/tarm/serial"
	"log"
	"os"
	"os/signal"
	"runtime"
	"strconv"
	"syscall"
	"time"
)

var count, zerocount int

func main() {
	os := runtime.GOOS
	log.Println(os)

	var c *serial.Config
	if os == "windows" {
		c = &serial.Config{
			Name:        "COM5",
			Baud:        9600,
			ReadTimeout: time.Second * 5,
			Parity:      serial.ParityNone,
			StopBits:    serial.Stop1}
	} else if os == "linux" {
		c = &serial.Config{
			Name:        "/dev/ttyUSB0",
			Baud:        9600,
			ReadTimeout: time.Second * 5,
			Parity:      serial.ParityNone,
			StopBits:    serial.Stop1}
	}

	s, err := serial.OpenPort(c)
	if err != nil {
		log.Println("===")
		log.Fatal(err)
	}
	defer s.Close()
	go shutdownRoutine()

	//Read and Send
	go ReceiveMsg(s)
	go SendMsg(s)

	select {}

}

func shutdownRoutine() {
	sigchan := make(chan os.Signal, 2)
	signal.Notify(sigchan, os.Interrupt)
	signal.Notify(sigchan, syscall.SIGTERM)
	<-sigchan
}

func SendMsg(p *serial.Port) {
	for {
		p.Write([]byte(strconv.Itoa(count) + "-"))
		log.Println("已收到：", count)

		time.Sleep(time.Second)
	}
}

func ReceiveMsg(p *serial.Port) {
	buf := make([]byte, 128)
	for {
		n, _ := p.Read(buf)
		if n == 0 {
			zerocount++
			// log.Println("zerocount：", zerocount)
			if zerocount == 3 { //连续3次超时，计数清理
				zerocount = 0
				count = 0
			}
		} else {
			zerocount = 0
		}
		count += n
		if n != 0 {
			time.Sleep(time.Millisecond * 100)
		}
	}
}
